import http from './http'

// ========= 按 PDF“接口文档-课程管理”精确对齐 =========
// 1. 列表接口
//   - 分页列表：GET /courses  支持查询参数：page,pageSize,name,subject,target
//   - 全部课程：GET /courses/list
//   - 按学科查询：GET /courses/subject/{subject}
//   响应统一：{ code, msg, data: { rows:[], total } }
// 2. 添加与修改接口
//   - 添加：POST /courses
//   - 修改：PUT  /courses  （修改需在请求体传 id，其他字段非必须）
//   返回统一：{ code:1, msg:'success', data:null }
// 3. 删除接口
//   - 删除：DELETE /courses/{id}

export const API = {
  endpoints: {
    // 列表
    list: '/courses',
    listAll: '/courses/list',
    listBySubject: (subject) => `/courses/subject/${encodeURIComponent(subject)}`,
    // 新增/修改/删除
    add: '/courses',
    update: '/courses', // 注意：PUT /courses，id在 body 内
    remove: (id) => `/courses/${id}`
  },
  // 查询参数映射（组件 -> 接口）
  // 组件使用的查询字段：{ page, pageSize, name, category, audience }
  // 接口的查询字段：{ page, pageSize, name, subject, target }
  queryMap: {
    page: 'page',
    pageSize: 'pageSize',
    name: 'name',
    category: 'subject',
    audience: 'target'
  },
  // 添加/修改时的字段映射（组件 -> 接口）
  payloadMap: {
    id: 'id',
    name: 'name',
    category: 'subject',
    price: 'price',
    audience: 'target',
    intro: 'description' // PDF字段为 description
  },
  // 响应结构映射（接口 -> 组件）
  // 注意：http.js 已在 code===1 时返回 r.data，因此这里不再加 data 根路径
  responseMap: {
    root: '',
    listKey: 'rows',
    totalKey: 'total'
  },
  // 单条记录字段映射（接口 -> 组件）
  itemMap: {
    id: ['id'],
    name: ['name'],
    category: ['subject'],
    price: ['price'],
    audience: ['target'],
    intro: ['description'],
    updatedAt: ['updateTime'],
    createdAt: ['createTime']
  }
}

// 课程学科与适用人群枚举映射
export const SUBJECT_LABEL_BY_CODE = {
  1: 'AI智能应用开发(Java)',
  2: 'AI大模型开发(Python)',
  3: 'AI鸿蒙开发',
  4: 'AI大数据',
  5: 'AI嵌入式',
  6: 'AI测试',
  7: 'AI运维'
}
export const TARGET_LABEL_BY_CODE = {
  1: '小白学员',
  2: '中级程序员',
  3: '高级程序员'
}

function invertMap(obj) {
  const m = {}
  Object.keys(obj).forEach((k) => { m[obj[k]] = Number(k) })
  return m
}
export const SUBJECT_CODE_BY_LABEL = invertMap(SUBJECT_LABEL_BY_CODE)
export const TARGET_CODE_BY_LABEL = invertMap(TARGET_LABEL_BY_CODE)

function toSubjectCode(val) {
  if (val === undefined || val === null || val === '') return undefined
  if (typeof val === 'number') return val
  const num = Number(val)
  if (!isNaN(num)) return num
  return SUBJECT_CODE_BY_LABEL[val]
}
function toTargetCode(val) {
  if (val === undefined || val === null || val === '') return undefined
  if (typeof val === 'number') return val
  const num = Number(val)
  if (!isNaN(num)) return num
  return TARGET_CODE_BY_LABEL[val]
}
function normalizeSubject(val) {
  if (val === undefined || val === null) return val
  const num = Number(val)
  if (!isNaN(num)) return SUBJECT_LABEL_BY_CODE[num] ?? String(val)
  return String(val)
}
function normalizeTarget(val) {
  if (val === undefined || val === null) return val
  const num = Number(val)
  if (!isNaN(num)) return TARGET_LABEL_BY_CODE[num] ?? String(val)
  return String(val)
}

// ========= 通用辅助 =========
function mapParams(params, map) {
  const out = {}
  Object.keys(params || {}).forEach((k) => {
    const target = map[k]
    if (!target) return
    out[target] = params[k]
  })
  return out
}

function deepGet(obj, path) {
  if (!path) return obj
  const segs = path.split('.').filter(Boolean)
  return segs.reduce((acc, key) => (acc && acc[key] !== undefined ? acc[key] : undefined), obj)
}

function pickFirst(obj, keys) {
  for (const k of keys) {
    if (obj[k] !== undefined && obj[k] !== null) return obj[k]
  }
  return undefined
}

function normalizeItem(obj) {
  const m = API.itemMap
  return {
    id: pickFirst(obj, m.id),
    name: pickFirst(obj, m.name),
    category: normalizeSubject(pickFirst(obj, m.category)),
    price: Number(pickFirst(obj, m.price)) || 0,
    audience: normalizeTarget(pickFirst(obj, m.audience)),
    intro: pickFirst(obj, m.intro),
    updatedAt: pickFirst(obj, m.updatedAt),
    createdAt: pickFirst(obj, m.createdAt)
  }
}

// ========= 课程接口 =========
export async function listCourses(params) {
  const reqParams = mapParams(params, API.queryMap)
  // 将 UI 的中文枚举转换为后端数值枚举
  if (reqParams.subject !== undefined) reqParams.subject = toSubjectCode(reqParams.subject)
  if (reqParams.target !== undefined) reqParams.target = toTargetCode(reqParams.target)
  const raw = await http.get(API.endpoints.list, { params: reqParams })
  const root = API.responseMap.root ? deepGet(raw, API.responseMap.root) : raw
  let list = []
  let total = 0
  if (root && typeof root === 'object') {
    const lk = API.responseMap.listKey
    const tk = API.responseMap.totalKey
    if (Array.isArray(root[lk])) {
      list = root[lk]
      total = Number(root[tk] ?? list.length) || list.length
    }
  } else if (Array.isArray(raw)) {
    list = raw
    total = raw.length
  }
  return { list: list.map(normalizeItem), total }
}

export async function listAllCourses() {
  const raw = await http.get(API.endpoints.listAll)
  const root = API.responseMap.root ? deepGet(raw, API.responseMap.root) : raw
  const rows = Array.isArray(root?.rows) ? root.rows : Array.isArray(root) ? root : []
  return rows.map(normalizeItem)
}

export async function listCoursesBySubject(subject) {
  const raw = await http.get(API.endpoints.listBySubject(subject))
  const root = API.responseMap.root ? deepGet(raw, API.responseMap.root) : raw
  const rows = Array.isArray(root?.rows) ? root.rows : Array.isArray(root) ? root : []
  return rows.map(normalizeItem)
}

export async function addCourse(payload) {
  const body = mapParams(payload, API.payloadMap)
  body.subject = toSubjectCode(body.subject)
  body.target = toTargetCode(body.target)
  body.price = Number(body.price) || 0
  return http.post(API.endpoints.add, body)
}

export async function updateCourse(id, payload) {
  // 兼容组件传 id 参数；实际接口要求 id 在 body
  const body = mapParams({ id, ...payload }, API.payloadMap)
  body.subject = toSubjectCode(body.subject)
  body.target = toTargetCode(body.target)
  body.price = Number(body.price) || 0
  return http.put(API.endpoints.update, body)
}

export async function removeCourse(id) {
  return http.delete(API.endpoints.remove(id))
}